package com.tian.comsumer;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.tian.constant.RabbitMQConstant;
import com.tian.message.UserGetCouponAdditionalMessage;
import com.tian.message.UserGetCouponMessage;
import com.tian.service.UserGetCouponAdditionalService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * {@code @description:} 用户领取优惠券后其他处理--消费消息
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-08-20 9:18
 * {@code @version:} 1.0
 */
@Slf4j
@RabbitListener(queues = RabbitMQConstant.USER_GET_COUPON_ADDITIONAL_QUEUE)
public class UserGetCouponAdditionalConsumer {
    @Resource
    private UserGetCouponAdditionalService userGetCouponAdditionalService;

    @RabbitHandler
    public void process(Object data, Channel channel, Message message) throws IOException {
        log.info("UserGetCouponAdditionalConsumer 用户领取优惠券-附加处理 消费者：{}", data);
        UserGetCouponAdditionalMessage userGetCouponAdditionalMessage = JSON.parseObject(new String(message.getBody()), UserGetCouponAdditionalMessage.class);
        try {
            boolean result = userGetCouponAdditionalService.process(userGetCouponAdditionalMessage);
            if (result) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        } catch (Exception e) {
            log.error("UserGetCouponAdditionalConsumer 消费者消费消息异常：{}", e.getMessage());
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }
}
